package com.zzstm.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zzstm.commonUtils.R;
import com.zzstm.eduservice.client.VodClient;
import com.zzstm.eduservice.entity.EduVideo;
import com.zzstm.eduservice.mapper.EduVideoMapper;
import com.zzstm.eduservice.service.EduVideoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzstm.servicebase.ex.GuliException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程视频 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2022-10-30
 */
@Service
public class EduVideoServiceImpl extends ServiceImpl<EduVideoMapper, EduVideo> implements EduVideoService {

    //注入VodClient
    @Autowired
    private VodClient vodClient;

    //跟库课程id删除课程和多个小节视频
    @Override
    public void removeVideoByCourseId(String courseId) {
        //跟库课程id查询小节的视频id
        QueryWrapper<EduVideo> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id",courseId);
        wrapper.select("video_source_id");
        List<EduVideo> videoList = baseMapper.selectList(wrapper);
        List<String> sourceIds = new ArrayList<>();
        for (EduVideo e : videoList){
            String videoSourceId = e.getVideoSourceId();
            if (!StringUtils.isEmpty(videoSourceId)){
                sourceIds.add(videoSourceId);
            }
        }
        if (sourceIds.size() > 0){
            vodClient.deleteBatch(sourceIds);
        }
        QueryWrapper<EduVideo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("course_id",courseId);
        baseMapper.delete(queryWrapper);
    }

    @Override
    public void removeVideoById(String videoId) {
        EduVideo video = baseMapper.selectById(videoId);
        String sourceId = video.getVideoSourceId();
        if (!StringUtils.isEmpty(sourceId)){
            //先删除阿里云的视频
            R r = vodClient.deleteAlyVideo(sourceId);
            if (r.getCode() == 20001){
                throw new GuliException(20001,"删除视频出错了，熔断器");
            }
        }
        //再删除数据库的视频信息
        baseMapper.deleteById(video);
    }
}
